<template>
  <div>
    <a-card :bordered="false">
      <title-name title="选择会议室" />

      <a-form-model
        ref="chooseRoomForm"
        :model="formData"
        :rules="rules"
      >
        <a-form-model-item
          label="会议室"
          prop="value"
        >
          <a-spin :spinning="meetRoomLoadding">
            <a-radio-group v-model="formData.value">
              <a-radio-button
                v-for="(item, index) in meetRoom"
                :key="item.id"
                class="meetroomlable"
                :value="item.id"
              >
                <span
                  class="redio-btn"
                  style=""
                >{{ item.name }}</span>
                <span>可容纳 {{ item.capacity }} 人</span>
                <a-divider type="vertical" />
                <span>{{ item.equipmentType.map((e, i) => { return e.name }).join('、') }}</span>
                <!-- <a-divider type="vertical"/>
                <span>开放预约时间段：00:00-23:59</span> -->
              </a-radio-button>
            </a-radio-group>
          </a-spin>
        </a-form-model-item>
        <a-form-model-item
          label="会议时间"
          prop="datetime"
        >
          <a-range-picker
            v-model="formData.datetime"
            :input-read-only="true"
            :disabled-date="disabledDate"
            :show-time="{ format: 'HH:mm', minuteStep: 30, defaultValue:defaulTime }"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            @blur="timeChange"
            @ok="timeChange"
          >
            <!-- :showTime.defaultValue="[moment('08:00'), moment('18:00')]" -->
          </a-range-picker>
        </a-form-model-item>
        <a-form-model-item label="会议室预约情况">
          <!-- :scroll="{ x: 1041, y: 400 }" -->
          <div
            class="time-table"
            style=""
          >
            <div class="thead">
              时间
            </div>
            <div
              v-for="(citem, idx) in columns"
              :key="idx"
              class="thead"
              :class="nowTimes.some(e => e.includes(citem.dayF)) ? 'nowchossedhead' : ''"
            >
              {{ citem.dayF + citem.week }}
            </div>
          </div>
          <div
            ref="scorlTab"
            class="scorl-tab"
            style=""
          >
            <div
              v-for="(item, index) in tabledata"
              :key="index"
              style="display: flex;"
            >
              <div class="table-item">
                {{ item.time }}
              </div>
              <div
                v-for="(subitem, idx) in columns"
                :key="idx"
                class="table-item"
              >
                <div class="sub-item">
                  <div
                    v-if="choseedTime.includes(subitem.day + ' ' + item.time)"
                    class="chossed"
                  >
                    <!-- {{item.time}} -->
                  </div>
                  <div
                    v-if="nowTimes.includes(subitem.day + ' ' + item.time)"
                    class="nowchossed"
                    :style="nowTimes.length == 1 ? {lineHeight: '12px'} : {}"
                  >
                    <template v-if="nowTimes.length == 1">
                      {{ item.time + ' - ' + item.time.replace(':0', ':3') }}
                    </template>
                    <template v-else>
                      <template v-if="nowTimes[0] == (subitem.day + ' ' + item.time)">
                        {{ item.time }}
                      </template>
                      <template v-if="nowTimes[nowTimes.length -1] == (subitem.day + ' ' + item.time)">
                        {{ item.time.replace(':0', ':3') }}
                      </template>
                    </template>
                  </div>
                </div>
                <div class="sub-item">
                  <div
                    v-if="choseedTime.includes(subitem.day + ' ' + item.time.replace(':0', ':3'))"
                    class="chossed"
                  >
                    <!-- {{item.time.replace(':0', ':3')}} -->
                  </div>
                  <div
                    v-if="nowTimes.includes(subitem.day + ' ' + item.time.replace(':0', ':3'))"
                    class="nowchossed"
                    :style="nowTimes.length == 1 ? {lineHeight: '12px'} : {}"
                  >
                    <template
                      v-if="nowTimes.length == 1"
                      style="line-height: 12px;"
                    >
                      {{ item.time.replace(':0', ':3') + ' - ' + (index == 23 ? '00:00' : (tabledata[index + 1].time)) }}
                    </template>
                    <template v-else>
                      <template v-if="nowTimes[0] == (subitem.day + ' ' + item.time.replace(':0', ':3'))">
                        {{ item.time.replace(':0', ':3') }}
                      </template>
                      <template v-if="nowTimes[nowTimes.length -1] == (subitem.day + ' ' + item.time.replace(':0', ':3'))">
                        {{ index == 23 ? '00:00' : (tabledata[index + 1].time) }}
                      </template>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-card>
    <div class="tool-btns">
      <a-button @click="handleClose">
        取消
      </a-button>
      <a-button
        type="primary"
        @click="handleSave('submit')"
      >
        确定
      </a-button>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { getMeetingRoomList, reservationTimeTable, reservationTimeAdjust } from '@/api/office/anualConference/index'
  const arr = [];
  function createData() {
    for (let i = 0; i < 24; i++) {
      // let { dataIndex } = tableColumns[i + 1];
      let time = i < 10 ? ('0' + i) + ':00' : i + ':00';
      arr.push({
        time: time,
        // dataIndex
      })
      // arr.push({time})
      // console.log(arr)
    }
  }
  createData()
  export default {
    name: 'ChoseRoom',
    components: {

    },
    props: {
      defaultValue: {
        type: [Object, null]
      },
      isDelete:{
        type:Boolean,
        default: false
      },
    },
    watch:{
    },
    data() {
      return {
        columns: [],
        tabledata: arr,
        meetRoomLoadding: false,
        allChoseedTime: [],
        defaulTime: [moment('08:00', 'HH:mm'), moment('08:30', 'HH:mm')],
        meetRoom: [],
        token:'',
        formData: {
          value: '',
          datetime: []
        },
        rules: {
          value: [{ required: true, message: '请选择会议室', trigger: 'change' }],
          datetime: [{ required: true, message: '请选择会议时间', trigger: 'blur' }],
        }
      }
    },
    created() {
      // console.log(this.moment('2021-04-20 00:00'))
    },
    computed: {
      nowTimes() {
        let result = [];
        if (this.formData.datetime.length) {
          let new_date = new Date(this.formData.datetime[1]);
          let old_date = new Date(this.formData.datetime[0]);
          // let new_date = new Date('2021-05-09 08:00:00');
          // let old_date = new Date('2021-05-08 18:00:00');
         result = this.getDateArray(old_date, new_date)
        }
        return result;
      },
      defTimes() {
        let result = [];
        let new_date = new Date(this.addressAndTime?.datetime[1]);
        let old_date = new Date(this.addressAndTime?.datetime[0]);
        // result = this.getDateArray(old_date, new_date)
        result = (this.formData.value == this.addressAndTime?.value?.id) ? this.getDateArray(old_date, new_date) : [];
        return result;
      },
      choseedTime() {
        const result = this.allChoseedTime.filter((item, index) => {
          const has = this.defTimes.some((e, i) => {
            return e == item;
          })
          return !has
        })
        return result
      },
      currentRoom() {
        const cur = this.meetRoom.filter((item, index) => {
          return item.id == this.formData.value
        })
        return cur.length ? cur[0] : null
      },
      addressAndTime() {
        return this.defaultValue
      },
      pageType() {
        return this.$route.query.pageType
      }
    },
    watch: {
      addressAndTime: {
        handler(nv, old) {
          if (nv) {
            this.formData.value = this.addressAndTime?.value.id
            this.formData.datetime = this.addressAndTime?.datetime
          }
        }
      },
      'formData.value': {
        handler(nv, old) {
          this.reservationTimeTable();
        }
      }
    },
    mounted() {
      var firefox = navigator.userAgent.indexOf('Firefox') != -1;
      this.$refs.scorlTab.onmousewheel = (e) => {
        if (e.stopPropagation) e.stopPropagation();
        else e.cancelBubble = true;
        if (e.preventDefault) e.preventDefault();
        else e.returnValue = false;
        var isUp = (firefox && e.detail < 0) || (!firefox && e.wheelDelta>0)
        var st = Math.max(this.$refs.scorlTab.scrollTop, document.documentElement.scrollTop);
        this.$refs.scorlTab.scrollTop = document.documentElement.scrollTop = st + (isUp ? -24 : 24);//一次滚动10px
      }
      this.$refs.scorlTab.scrollTop = 400
      this.getMeetingRoomList();
      this.columns = this.creatTData();

    },
    methods: {
      moment,
      disabledDate(current) {
        return current && (current < moment().startOf('day')  || current > moment(new Date(new Date().toLocaleDateString()).getTime() + 15*24*60*60*1000))
      },
      reservationTimeTable() {
        const param = {
          query: {
            meetingRoomId: this.formData.value
          }
        }
        this.allChoseedTime = [];
        reservationTimeTable(param).then((res) => {
          if (res && res.code == 200) {
            let list = [];
            res.data.map((item, index) => {
              const start = new Date(item.start);
              const end =  new Date(item.end);
              list = list.concat(this.getDateArray(start, end))
            })
            // console.log(all)
            this.allChoseedTime = list//timeDatas.data;
            this.timeChange();
            // console.log(all)
          }
        })
      },
      creatTData(data) {
        let now = new Date();
        let nowTime = now.getTime() ;
        let oneDayTime = 24*60*60*1000 ;
        const result = [];
        for(let i = 0 ; i < 15 ; i++){

          //显示周一
          let ShowTime = nowTime + (i)*oneDayTime ;
          //初始化日期时间
          let myDate = new Date(ShowTime);
          let year = myDate.getFullYear();
          let month = (myDate.getMonth() + 1) < 10 ? '0' + (myDate.getMonth() + 1) : myDate.getMonth() + 1;
          let date = myDate.getDate() < 10 ? '0' + myDate.getDate() : myDate.getDate();
          let str = "周" + "日一二三四五六".charAt(myDate.getDay());
          const obj = {
            day: year+"."+month+"."+date,
            dayF: month+"."+date,
            week: str
          }
          result.push(obj)
        }
        return result
      },
      handleSave() {
        this.$refs.chooseRoomForm.validate().then((valid) => {
          if (valid) {
            const times = {
              datetime: this.formData.datetime,
              value: this.currentRoom
            }

            if (this.pageType === 'adjust') {
              let param = {
                "startTime": this.formData.datetime[0],
                "endTime": this.formData.datetime[1],
                "id": this.$route.query.id,
                "meetingRoomId": this.formData.value
              }
              reservationTimeAdjust(param).then((res) => {
                console.log(res)
                if (res && res.data && res.data.code == 200) {
                  this.$message.success('保存成功！')
                  this.$multiTab.close(this.$route.fullpath);
                } else {
                  this.$message.error('修改失败！')
                }
              })
            } else {
              this.$emit('ok', times)
            }
            return
          } else {
            this.$message.error('请选择会议时间地点！')
          }
        })
      },
      timeChange() {
        if (this.formData.datetime.length == 0) return;
        let new_date = new Date(this.formData.datetime[1]); //新建一个日期对象，默认现在的时间
        let old_date = new Date(this.formData.datetime[0]); //设置过去的一个时间点，"yyyy-MM-dd HH:mm:ss"格式化日期

        if (old_date.getTime() >= new_date.getTime()) {
          this.$message.error('结束时间不能小于等于开始时间！')
          setTimeout(() => {
            this.formData.datetime = [];
          }, 500)
          return;
        }
        const now = this.getDateArray(old_date, new_date)
        const repeat = now.filter((item, index) => {
          return this.choseedTime.some((e, i) => {
            return e == item
          })
        })
        if (repeat.length) {
          setTimeout(() => {
            this.$error({
              title: '温馨提示',
              okText: '确定',
              content: '选择的时间段已被预订，请重新选择',
            });
            this.formData.datetime = [];
          }, 500)
        }
      },
      getDateArray(start, end) {
        const space = 30 * 60 * 1000;
        let startDate = start.getTime();
        let endDate = end.getTime() - space;
        let mod = endDate - startDate;
        let dateArray = [];
        while (mod > space) {
          let d = new Date();
          d.setTime(startDate + space);
          dateArray.push(d);
          mod = mod - space;
          startDate = startDate + space;
        }
        dateArray.unshift(new Date(start.getTime()));

        dateArray.push(new Date(endDate));

        const list = {}
        let a = []
        dateArray.map(item => {
          const y = item.getFullYear();
          const m = (item.getMonth() + 1) < 10 ? '0' + (item.getMonth() + 1) : (item.getMonth() + 1);
          const d = item.getDate() < 10 ? '0' + item.getDate() : item.getDate();
          const h = item.getHours() < 10 ? '0' + item.getHours() : item.getHours();
          const M = item.getMinutes() < 10 ? '0' + item.getMinutes() : item.getMinutes();
          const key = y + '.' + m + '.' + d;
          item = key + ' ' + h + ":" + M;
          if (!list[key]) {
            list[key] = []
          }
          list[key].push(item)
          if (a.indexOf(item) === -1) {
            a.push(item);
          }
        });
        // console.log(list);
        // console.log(a);
        return a;
      },
      async getMeetingRoomList() {
        this.meetRoomLoadding = true;
        let param = {pageNo: 1, pageSize: 100, query: {enable: true, unitId: this.$userInfo().currentPost.id}}//
        let res = await getMeetingRoomList(param);
        this.meetRoomLoadding = false;
        if (res && res.code == 200) {
          this.meetRoom = res.data
          if (this.addressAndTime) {
            this.formData.value = this.addressAndTime.value.id
            this.formData.datetime = this.addressAndTime?.datetime
          } else {
            if (res.data.length) this.formData.value = res.data[0].id;
          }
        }
      },
      handleClose() {
        if (this.pageType === 'adjust') {
          this.$multiTab.close(this.$route.fullpath)
        } else {
          this.$emit('cancel')
        }
      }
    },
  }

</script>

<style scoped>
  .tool-btns .ant-btn{
    margin-left: 12px;
   }
  .ant-form-item {
    display: flex;
  }
  .redio-btn {
    text-align: center;
    background: #e1e1e1;
    width: 290px;
    position: absolute;
    left: 0;
    height: 28px;
  }
  .ant-radio-button-wrapper-disabled{
    color: rgba(0, 0, 0, 0.65);
    background: #fff;
  }
  .ant-radio-button-wrapper-disabled.ant-radio-button-wrapper-checked .redio-btn{
    color: #fff;
    background: #108ee9;
  }
  .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled) .redio-btn,{
    color: #fff;
    background: #108ee9;
  }
  .ant-radio-button-wrapper.meetroomlable {
      display: block;
      height: 30px;
      line-height: 30px;
      margin-bottom: 10px;
      position: relative;
      padding-left: 300px
  }
  .ant-calendar-picker {
    width: 200px;
  }
  .reservationInfo{
    height: 300px;
  }
  .time-table {
    overflow: hidden;
    /* border-left: 1px solid #c8c8c8;border-top: 1px solid #c8c8c8;; */
    border-left: 1px solid #c8c8c8;
  }
  .time-table:first-child {
  }
  .thead{
    border-top: 1px solid #c8c8c8;
    border-right: 1px solid #c8c8c8;
    border-bottom: 1px solid #c8c8c8;
    width: 60px;
    height: 50px;
    float: left;
    text-align: center;
    font-weight: 500;
    line-height: 1;
    color: #333;
    align-items: center;
    padding: 10px;
    display: flex;
    vertical-align: middle;
  }
  .scorl-tab {
    border-left: 1px solid #c8c8c8;
    height: 528px;
    overflow: auto;
    width: 978px;
  }
  .table-item {
    border-right: 1px solid #c8c8c8;
    border-bottom: 1px solid #c8c8c8;
    width: 60px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    /* height: 100px; */
    /* float: left; */
  }
  .table-item .sub-item {
    /* height: 50px; */
    height: 25px;
    line-height: 25px;
    border-bottom: 1px dotted #c8c8c8;
  }
  .chossed {
    background: #eee;
    width: 100%;
    height: 100%;
  }
  .nowchossed {
    color: #fff;
    background: #1890ff;
    width: 100%;
    height: 100%;
  }
  .nowchossedhead {
    color: #1890ff;
  }
</style>
